# from uuapp.models import OrderInfo, OrderGoods
from django.views import View

# from uuapp.utils.bootstrap import BootStrapModelForm  # ,LoginForm
# from uuapp.utils.encrypt import md5
import hashlib
from django.shortcuts import render, redirect
from django.http import HttpResponse
from uuapp import models
from uuapp.models import ProductCategory, Product  # ,User
from django.core.paginator import Paginator
import time
# from uuapp.utils.bootstrap import BootStrapModelForm
def api_products(request):
    """
    API endpoint to return product data in JSON format
    """
    products = Product.objects.all().values('product_code', 'name', 'price')
    return JsonResponse(list(products), safe=False)
# cashier
def cashier(request):
     from .models import ProductCategory, Product

def cashier(request):
    categories = ProductCategory.objects.all()
    Product_list = Product.objects.filter(stock__gt=0)##获取库存大于0的所有产品。
    return render(request, 'cashier.html', {'categories': categories, 'Product_list': Product_list})

from django.views.decorators.csrf import csrf_exempt
# 商品分类API
from django.core import serializers
# uuapp/views.py
from django.views.generic import DetailView
from .models import Product

class ProductDetailView(DetailView):
    model = Product
    template_name = 'product_detail.html'  # 确保有这个模板文件
class CategoryListView(View):
    def get(self, request):
        categories = ProductCategory.objects.all().values('id', 'name', 'parent')
        return JsonResponse(list(categories), safe=False)

# 商品列表API
class ProductListView(View):
    def get(self, request):
        queryset = Product.objects.filter(stock__gt=0).select_related('category')
        
        # 分类筛选
        category_id = request.GET.get('category_id')
        if category_id:
            # 获取所有子分类ID
            subcategories = ProductCategory.objects.filter(
                Q(id=category_id) | Q(parent=category_id)
            ).values_list('id', flat=True)
            queryset = queryset.filter(category__in=subcategories)
        
        # 搜索功能
        search = request.GET.get('search')
        if search:
            queryset = queryset.filter(
                Q(name__icontains=search) | 
                Q(description__icontains=search) |
                Q(product_code__icontains=search)
            )
        
        data = []
        for product in queryset:
            data.append({
                'product_code': product.product_code,
                'name': product.name,
                'price': float(product.price),
                'description': product.description,
                'stock': product.stock,
                'unit': product.unit,
                'specification': product.specification,
                'shelf_life_end_date': product.shelf_life_end_date.strftime('%Y-%m-%d') if product.shelf_life_end_date else None,
                'image_url': product.image_url,
                'category': product.category_id
            })
        
        return JsonResponse(data, safe=False)

# URL配置补充 (urls.py)


# 这行是下面用
# 				<!-- url 'user:user'##user: 是指模块名user' ##:user' 是路劲名 path('user/',views.UserInfoView.as_view()) -->
# 			 <li><a href="{% url 'user:user' %}" class="active">· 个人信息</a></li> -->
# 				<a href="{% url 'user:user' %}" {% if page == 'user' %}class="active"{% endif %}>· 个人信息</a></li>
# 				<li><a href="{% url 'user:order' %}" {% if page == 'order' %}class="active"{% endif %}>· 全部订单</a></li>
# 				<li><a href="{% url 'user:address' %}" {% if page == 'address' %}class="active"{% endif %}>· 收货地址</a></li>

# ---------两层菜单系统2022-11-14前------------------------
# views.py
from django.views.generic import DetailView
from .models import ProductCategory

class CategoryDetailView(DetailView):
    model = ProductCategory
    template_name = 'category_detail.html'  # 确保有这个模板文件

def index(request):
<<<<<<< HEAD
    # 获取顶级分类
    top_categories = ProductCategory.objects.filter(parent=None)
    
    # 获取精选商品（示例：价格最高的8个商品）
    featured_products = Product.objects.order_by('-price')[:8]
    
    # 获取所有商品用于搜索和过滤
    all_products = Product.objects.all()
    
    # 处理搜索逻辑
    search_term = request.GET.get('search', '')
    min_price = request.GET.get('min_price', None)
    max_price = request.GET.get('max_price', None)
=======
     """首页"""
     categories = models.ProductCategory.objects.all()
     products = models.Product.objects.all()
     
     return render(request, 'index.html', {
         'categories': categories,
         'products': products
     })

    # # ##登入--进入首页 要先到登入--用了中间件，就不用这儿了
    # # info =request.session.get("info")
    # # if not info:
    # #     return redirect('/login/')
    # # 查询商品的分类
    # categories = models.ProductCategory.objects.all()
>>>>>>> 0ac75087e5e07a3ef0624f7a4a9866c7346941b7

    # for cag in categories:
    #     # models.GoodInfo.objects.filter(goods_cag=cag)
    #     # 一对多,查询多的一方,会在这样=一方有一个属性，多的一方，模型类名小写-set
    #     # cag.goods_list = cag.Product_set.all().order_by('-id')

    #     # 反向获取4个  # order_by('-id')[:4]##  ##获取倒数4个列表
    #     # cag.goods_list = cag.Product_set.order_by(
    #     #     '-id')[:6]  # Product_set 小写呀类对应下的所有
    #     # 获取所有商品cookies key:value 商品的id：数字
    #     # 购物车商品的列表
    #     cart_goods_list = []
    #     # 购物车总数量
    #     cart_goods_count = 0
    #     # 对id 遍历数量
    #     for goods_id, goods_num in request.COOKIES.items():
    #         # 判断商品id 是否数字,如果不是，下次循环
    #         if not goods_id.isdigit():
    #             continue
    #         # 获取当前遍历到商品
    #         cart_goods = Product.objects.filter(id=goods_id).first()
    #         if not cart_goods:
    #             continue
    #         cart_goods.goods_num = goods_num
    #         # 把商品存放到列表里

    #         cart_goods_list.append(cart_goods)
    #         # 累加所以的商品##购物车商品的总数量 -- int(goods_num)
    #         cart_goods_count = cart_goods_count + int(goods_num)

<<<<<<< HEAD
    context = {
        'categories': top_categories,
        'featured_products': featured_products,
        'products': all_products,
        'search_term': search_term,
        'min_price': min_price,
        'max_price': max_price
    }
    return render(request, 'index.html', context)
# def goods(request):
#     """
#     View to display all products
#     """
#     products = Product.objects.all()
#     return render(request, 'goods.html', {'products': products})

def detail(request, product_id=None):
    """
    商品详情页视图
    功能：
    1. 显示商品详细信息
    2. 处理缺失product_id的情况
    3. 提供加入购物车功能
    4. 显示相关商品推荐
    """
    if not product_id:
        return redirect('index')
        
    try:
        # 获取商品详情并优化查询
        product = Product.objects.select_related('category').get(id=product_id)
        
        # 获取同分类的其他商品作为推荐(排除当前商品)
        related_products = Product.objects.filter(
            category=product.category
        ).exclude(id=product.id).order_by('?')[:4]  # 随机取4个
        
        # 获取热门商品推荐
        popular_products = Product.objects.order_by('-sales')[:4]
        
        return render(request, 'detail.html', {
            'product': product,
            'related_products': related_products,
            'popular_products': popular_products,
            'product_details': product.details or "暂无详细描述"
        })
        
    except Product.DoesNotExist:
        raise Http404("商品不存在")

def goods(request):
    """
    View to display products with category tree and grouped products
    """
    # 获取顶级分类及其子分类
    top_categories = ProductCategory.objects.filter(parent=None).prefetch_related('subcategories')
    
    # 获取所有商品基础查询集
    products = Product.objects.all()
    
    # 处理分类筛选
    selected_category = None
    category_id = request.GET.get('category_id')
    if category_id:
        try:
            selected_category = ProductCategory.objects.get(id=category_id)
            # 获取当前分类及其所有子分类的商品
            products = products.filter(
                category__in=selected_category.get_descendants(include_self=True)
            )
        except ProductCategory.DoesNotExist:
            pass
    
    # 处理搜索
    search_term = request.GET.get('search', '')
    if search_term:
        from django.db import models
        products = products.filter(
            models.Q(product_code__icontains=search_term) |
            models.Q(name__icontains=search_term)
        )
    
    # 按分类分组商品
    categorized_products = {}
    for category in ProductCategory:
        category_products = products.filter(
            category__in=category.get_descendants(include_self=True)
        )[:12]  # 每个分类最多显示12个商品
        if category_products.exists():
            categorized_products[category] = category_products
    
    context = {
        'ProductCategory': ProductCategory,
        'categorized_products': categorized_products,
        'selected_category': selected_category,
        'search_term': search_term
    }
    return render(request, 'goods.html', context)

# def show_cart(request):
#     """
#     Display shopping cart items
#     """
#     cart_items = []
#     total_price = 0
    
#     if 'cart' in request.session:
#         cart = request.session['cart']
        
#         for Product_id, quantity in cart.items():
#             try:
#                 Product = Product.objects.get(id=Product_id)
#                 item_total = Product.Product_price * quantity
#                 cart_items.append({
#                     'Product': Product,
#                     'quantity': quantity,
#                     'item_total': item_total
#                 })
#                 total_price += item_total
#             except Product.DoesNotExist:
#                 continue
    
#     context = {
#         'cart_items': cart_items,
#         'total_price': total_price
#     }
    
#     return render(request, 'cart.html', context)

# def add_cart(request):
#     """
#     View to handle adding items to shopping cart
#     """
#     Product_id = request.GET.get('id')
#     quantity = int(request.GET.get('quantity', 1))
    
#     if not Product_id:
#         return HttpResponse('商品ID不能为空', status=400)
    
#     try:
#         Product = ProductInfo.objects.get(id=Product_id)
#     except ProductInfo.DoesNotExist:
#         return HttpResponse('商品不存在', status=404)
    
#     # Initialize cart in session if not exists
#     if 'cart' not in request.session:
#         request.session['cart'] = {}
    
#     # Update cart quantity
#     cart = request.session['cart']
#     cart[Product_id] = cart.get(Product_id, 0) + quantity
#     request.session.modified = True
    
#     return JsonResponse({'status': 1, 'msg': '商品已添加到购物车'})
=======
    #         # 参数1请求的对象request ,2 需要返回的html 3 需要传入到模板里的数据
    # return render(request, 'index.html', {
    #     'categories': categories,
    #     'cag.goods_list': cag.product_set.all(),
    #     'cart_goods_list': cart_goods_list,
    #     'cart_goods_count': cart_goods_count
    # })

from django.views import View
from django.shortcuts import render
from django.core.paginator import Paginator
from django.db.models import Count, Prefetch
from django.http import HttpResponseServerError
import logging
from . import models

logger = logging.getLogger(__name__)

class GoodsView(View):
    def get(self, request):
        try:
            # 获取所有分类（包含子分类关系）
            categories = models.ProductCategory.objects.annotate(
                product_count=Count('products')
            ).prefetch_related('subcategories')
            
            # 获取当前选中分类ID
            current_category_id = request.GET.get('cag')
            current_category = None
            
            # 构建基础查询集（包括预取关联数据）
            products_queryset = models.Product.objects.select_related('category').all()
            
            # 如果有分类筛选
            if current_category_id:
                try:
                    current_category = models.ProductCategory.objects.get(id=current_category_id)
                    # 获取该分类及其所有子分类的商品
                    subcategories = current_category.subcategories.all()
                    categories_ids = [current_category.id] + list(subcategories.values_list('id', flat=True))
                    products_queryset = products_queryset.filter(category__id__in=categories_ids)
                except models.ProductCategory.DoesNotExist:
                    logger.warning(f"Category not found: {current_category_id}")
            
            # 分页处理
            paginator = Paginator(products_queryset, 12)  # 每页12个商品
            page_number = request.GET.get('page', 1)
            page_obj = paginator.get_page(page_number)
            
            # 准备上下文数据
            context = {
                'categories': categories,
                'page_data': page_obj,
                'paginator': paginator,
                'current_category': current_category,
            }
            
            # 如果当前分类没有商品，获取其他分类的热门商品
            if not page_obj.object_list.exists() and current_category:
                other_categories = models.ProductCategory.objects.exclude(
                    id=current_category.id
                ).annotate(
                    product_count=Count('products')
                ).filter(
                    product_count__gt=0
                ).order_by('-product_count')[:16]
                
                # 预取每个分类的2个商品（按创建时间倒序）
                other_categories = other_categories.prefetch_related(
                    Prefetch(
                        'products',
                        queryset=models.Product.objects.order_by('-id')[:5],
                        to_attr='prefetched_products'
                    )
                )
                context['other_categories'] = other_categories
            else:
                context['other_categories'] = None
            
            logger.info(f"Rendering goods page with {page_obj.object_list.count()} products")
            return render(request, 'goods.html', context)
            
        except Exception as e:
            logger.error(f"Error in GoodsView: {str(e)}", exc_info=True)
            # 可以自定义错误页面或返回JSON响应
            return HttpResponseServerError("服务器错误，请稍后再试")
>>>>>>> 0ac75087e5e07a3ef0624f7a4a9866c7346941b7

from django.shortcuts import render, redirect
from django.http import JsonResponse
from django.contrib.auth.decorators import login_required
from.models import  Product
from django.utils.decorators import method_decorator
from django.views import View

# 商品详情页视图
class DetailView(View):
    def get(self, request):
        categories = models.Product.objects.all()
        cart_goods_count = 0
        cart_goods_list = []

<<<<<<< HEAD


# def show_cart(request):
#     """
#     Display shopping cart items
#     """
#     cart_items = []
#     total_price = 0
    
#     if 'cart' in request.session:
#         cart = request.session['cart']
        
#         for Product_id, quantity in cart.items():
#             try:
#                 Product = Product.objects.get(id=Product_id)
#                 item_total = Product.Product_price * quantity
#                 cart_items.append({
#                     'Product': Product,
#                     'quantity': quantity,
#                     'item_total': item_total
#                 })
#                 total_price += item_total
#             except Product.DoesNotExist:
#                 continue
    
#     context = {
#         'cart_items': cart_items,
#         'total_price': total_price
#     }
    
#     return render(request, 'cart.html', context)

# def add_cart(request):
#     """
#     Add Product to shopping cart
#     """
#     Product_id = request.GET.get('id')
#     quantity = int(request.GET.get('quantity', 1))
    
#     # Get Product info
#     try:
#         Product = Product.objects.get(id=Product_id)
#     except Product.DoesNotExist:
#         return JsonResponse({'status': 0, 'errmsg': '商品不存在'})
    
#     # Initialize cart in session if not exists
#     if 'cart' not in request.session:
#         request.session['cart'] = {}
    
#     cart = request.session['cart']
    
#     # Add or update Product in cart
#     if Product_id in cart:
#         cart[Product_id] += quantity
#     else:
#         cart[Product_id] = quantity
    
#     # Save cart to session
#     request.session['cart'] = cart
    
#     return JsonResponse({'status': 1, 'msg': '添加成功'})


def order_Product(request):
    """
    Display ordered Product
    """
    if not request.user.is_authenticated:
        return redirect('login')
        
    ordered_items = OrderProduct.objects.filter(user=request.user).select_related('Product')
    
    context = {
        'ordered_items': ordered_items
    }
    
    return render(request, 'order_Product.html', context)


def user_center(request):
    """
    Display user center page with user info and order history
    """
    if not request.user.is_authenticated:
        return redirect('login')
        
    # Get user's orders through Product_order relationship
    orders = OrderProduct.objects.filter(Product_order__user=request.user).select_related('Product')
    
    context = {
        'user': request.user,
        'orders': orders
    }
    
    return render(request, 'user_center.html', context)


def order_confirmation(request, order_id):
    """
    Display order confirmation details
    """
    if not request.user.is_authenticated:
        return redirect('login')
        
    order = get_object_or_404(OrderProduct, id=order_id, user=request.user)
    
    context = {
        'order': order,
        'order_items': order.Product.all()
    }
    
    return render(request, 'order_confirmation.html', context)


def cart_products(request):
    """
    View to display all cart products
    """
    cart_products = CartProducts.objects.all().select_related('product')
    
    context = {
        'cart_products': cart_products
    }
    
    return render(request, 'cart_products.html', context)


def remove_from_cart(request):
    """
    View to remove items from shopping cart
    """
    Product_id = request.POST.get('Product_id')
    
    if not Product_id:
        return JsonResponse({'status': 0, 'errmsg': '商品ID不能为空'})
    
    if 'cart' not in request.session:
        return JsonResponse({'status': 0, 'errmsg': '购物车为空'})
    
    cart = request.session['cart']
    
    if Product_id in cart:
        del cart[Product_id]
        request.session.modified = True
        return JsonResponse({'status': 1, 'msg': '商品已从购物车移除'})
    else:
        return JsonResponse({'status': 0, 'errmsg': '商品不在购物车中'})


def update_cart(request):
    """
    View to update cart item quantities
    """
    if request.method != 'POST':
        return JsonResponse({'status': 0, 'errmsg': 'Invalid request method'}, status=400)
    
    Product_id = request.POST.get('id')
    quantity = int(request.POST.get('quantity', 1))
    
    if not Product_id:
        return JsonResponse({'status': 0, 'errmsg': '商品ID不能为空'}, status=400)
    
    try:
        Product = Product.objects.get(id=Product_id)
    except Product.DoesNotExist:
        return JsonResponse({'status': 0, 'errmsg': '商品不存在'}, status=404)
    
    if 'cart' not in request.session:
        return JsonResponse({'status': 0, 'errmsg': '购物车为空'}, status=400)
    
    cart = request.session['cart']
    
    if quantity <= 0:
        # Remove item if quantity is 0 or negative
        cart.pop(Product_id, None)
    else:
        # Update quantity
        cart[Product_id] = quantity
    
    request.session['cart'] = cart
    request.session.modified = True
    
    return JsonResponse({'status': 1, 'msg': '购物车更新成功'})


def checkout(request):
    """
    View to handle order checkout process
    """
    if not request.user.is_authenticated:
        return redirect('login')
        
    if 'cart' not in request.session or not request.session['cart']:
        return redirect('show_cart')
    
    # Create order from cart items
    cart = request.session['cart']
    order = OrderInfo.objects.create(user=request.user)
    
    for Product_id, quantity in cart.items():
=======
        if request.user.is_authenticated:
            try:
                cart = ShoppingCarts.objects.get(user=request.user)
                cart_products = CartProducts.objects.filter(cart=cart)
                for cart_product in cart_products:
                    cart_goods_list.append(cart_product.product)
                    cart_goods_count += cart_product.quantity
            except (ShoppingCarts.DoesNotExist, CartProducts.DoesNotExist):
                pass

        goods_id = request.GET.get('id', 1)
>>>>>>> 0ac75087e5e07a3ef0624f7a4a9866c7346941b7
        try:
            goods_data = models.Product.objects.get(id=goods_id)
        except Product.DoesNotExist:
            return redirect('/')  # 商品不存在时重定向到首页

        return render(request, 'detail.html', {
            'categories': categories,
            'cart_goods_list': cart_goods_list,
            'cart_goods_count': cart_goods_count,
            'goods_data': goods_data
        })
    
from django.shortcuts import get_object_or_404, render
from .models import Product

def detail_view(request):
    product_id = request.GET.get('id')
    product = get_object_or_404(Product, id=product_id)
    return render(request, 'detail.html', {'product': product})    

# 添加商品到购物车视图
@login_required
def add_cart(request):
    goods_id = request.GET.get('id')
    if goods_id:
        try:
            cart = ShoppingCarts.objects.get(user=request.user)
            product = Product.objects.get(id=goods_id)
            cart_product, created = CartProducts.objects.get_or_create(
                cart=cart,
                product=product,
                defaults={'quantity': 1}
            )
            if not created:
                cart_product.quantity += 1
                cart_product.save()
        except (ShoppingCarts.DoesNotExist, Product.DoesNotExist):
            pass
    return redirect(request.META.get('HTTP_REFERER', '/'))  # 重定向回上一页或首页

# 显示购物车视图
class ShowCartView(View):
    @method_decorator(login_required)
    def get(self, request):
        cart_goods_list = []
        cart_goods_count = 0
        cart_goods_money = 0

        try:
            cart = ShoppingCarts.objects.get(user=request.user)
            cart_products = CartProducts.objects.filter(cart=cart)
            for cart_product in cart_products:
                product = cart_product.product
                product.goods_num = cart_product.quantity
                product.total_money = cart_product.quantity * product.goods_price
                cart_goods_list.append(product)
                cart_goods_count += cart_product.quantity
                cart_goods_money += cart_product.quantity * product.goods_price
        except (ShoppingCarts.DoesNotExist, CartProducts.DoesNotExist):
            pass

        return render(request,'show_cart.html', {
            'cart_goods_list': cart_goods_list,
            'cart_goods_count': cart_goods_count,
            'cart_goods_money': cart_goods_money,
        })

# 更新购物车商品数量视图
@login_required
def update_quantity(request):
    if request.method == 'POST':
        product_id = request.POST.get('product_id')
        new_quantity = request.POST.get('quantity')

        try:
            cart = ShoppingCarts.objects.get(user=request.user)
            product = Product.objects.get(id=product_id)
            cart_product = CartProducts.objects.get(cart=cart, product=product)
            cart_product.quantity = int(new_quantity)
            cart_product.save()
            return JsonResponse({'status':'success','message': '数量更新成功'})
        except (Product.DoesNotExist, ShoppingCarts.DoesNotExist, CartProducts.DoesNotExist):
            return JsonResponse({'status': 'error','message': '未找到相关记录'})
        except ValueError:
            return JsonResponse({'status': 'error','message': '数量格式错误'})
    return JsonResponse({'status': 'error','message': '请求方法错误'})


def remove_cart(request):
    # 删除商品
    # 获取商品要删除de id
    goods_id = request.GET.get('id', '')
    if goods_id:

        # 获取一个页面的url
        prev_url = request.META['HTTP_REFERER']

        # 重定向到上一个页面
        response = redirect(prev_url)
        goods_count = request.COOKIES.get(goods_id, '')
        if goods_count:
            response.delete_cookie(goods_id)
    return response
    # 跳转参考
    # return redirect("/tongy/list/")
    # return HttpResponse("success")


def plate_order(request):
    # if request.path_info =="/user/login/":
    #     return

    # 先login 再到购物车--中间件插入
    # info_dict = request.session.get("info")
    # if not info_dict:
    #     return redirect('/user/login/')

    # 购物车的所有商品
    cart_goods_list = []
    cart_goods_count = 0
    cart_goods_money = 0

    for goods_id, goods_num in request.COOKIES.items():
        #     # 验证goods_id 是不是一个数字--关键
        if not goods_id.isdigit():
            continue
        cart_goods = Product.objects.get(id=goods_id)

        cart_goods.goods_num = goods_num
    #     # 计算小计价格
        cart_goods.total_money = cart_goods.goods_price * int(goods_num)
        cart_goods_list.append(cart_goods)
    #     # 总计
        cart_goods_count += int(goods_num)
        # 累计总价
        cart_goods_money += cart_goods.goods_price * int(goods_num)
    return render(request, 'plate_order.html', {
        'cart_goods_list': cart_goods_list,
        'cart_goods_count': cart_goods_count,
        'cart_goods_money': cart_goods_money
    })

# get_list


# def goods_listtwo(request):

<<<<<<< HEAD

def add_cart(request):
    """
    Add goods to shopping cart
    """
    goods_id = request.GET.get('id')
    quantity = int(request.GET.get('quantity', 1))
    
    if not goods_id:
        return JsonResponse({'status': 0, 'errmsg': '商品ID不能为空'})
    
    try:
        goods = GoodsInfo.objects.get(id=goods_id)
    except GoodsInfo.DoesNotExist:
        return JsonResponse({'status': 0, 'errmsg': '商品不存在'})
    
    # Initialize cart in session if not exists
    if 'cart' not in request.session:
        request.session['cart'] = {}
    
    cart = request.session['cart']
    
    # Add or update goods in cart
    if goods_id in cart:
        cart[goods_id] += quantity
    else:
        cart[goods_id] = quantity
    
    # Save cart to session
    request.session['cart'] = cart
    
    # Create redirect response
    prev_url = request.META.get('HTTP_REFERER', '/')
    response = redirect(prev_url)
    
    # Set cookie with the quantity of the added goods
    response.set_cookie(goods_id, quantity)
    
    return response
=======
#     data_list = Product.objects.all()

#     # print(data_list)

#     return render(request, 'goods_list.html', {"data_list": data_list})

#     # -----查看goods详情数据--数据库查询-------------------------


# def goods_list(request):

#     # data_list = Product.objects.all()

#     # # print(data_list)

#     # return render(request, 'goods_list.html',{"data_list":data_list})
#     """搜素"""
#     data_dict = {}
#     search_data = request.GET.get('q', "")
#     if search_data:
#         data_dict["goods_name__contains"] = search_data  # "price__contains"

#     queryset = models.Product.objects.filter(
#         **data_dict).order_by("-id")  # PrettyNum -- 来自model

# # -------分页生效-----------------
#     # """goods"""
#     # 1获取传过来分类id
#     # 要有id
#     # --这儿正常--前面没搞对--'cag.id'情况全变成aa类，/'cag=int(cag)'况全变成aa类,但现在提示没id, 'cag',1
#     cag_id = request.GET.get('cag', 1)

#     # #获取当前的页码
#     page_id = request.GET.get('page', 1)
#     # 获取当前的分类对象
#     # 提示分页下面一行报错#?????? 提示分页下面一行报错# 提示分页下面一行报错# 提示分页下面一行报错
#     current_cag = ProductCategory.objects.get(id=cag_id)  # 首先方案1
#     # current_cag = current_cag.Product.set.all()##方案2
#     # current_cag = Product.objects.filter(goods_cag=current_cag)##方案3
#     # 获取当前的分类下的所有商品
#     goods_data = Product.objects.filter(
#         goods_cag_id=cag_id).order_by('-id')  # Product
#     # print(goods_data)
>>>>>>> 0ac75087e5e07a3ef0624f7a4a9866c7346941b7
